package com.dcy.znoa.service.attendance.impl;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.dcy.znoa.common.exception.BusinessException;
import com.dcy.znoa.common.util.DateUtil;
import com.dcy.znoa.common.util.ZnoaConstant;
import com.dcy.znoa.common.util.pojo.JsonCommon;
import com.dcy.znoa.common.util.pojo.JsonForList;
import com.dcy.znoa.controller.attendance.model.attRule.SelectAttRuleModel;
import com.dcy.znoa.controller.publiz.model.SelectBaseModel;
import com.dcy.znoa.controller.publiz.model.company.SelectCompanyModel;
import com.dcy.znoa.dao.attendance.AttRuleAddressDao;
import com.dcy.znoa.dao.attendance.AttRuleDao;
import com.dcy.znoa.dao.publiz.CompanyDao;
import com.dcy.znoa.dao.publiz.DepartmentDao;
import com.dcy.znoa.dao.user.OperDao;
import com.dcy.znoa.domain.Oper;
import com.dcy.znoa.domain.attendance.AttRule;
import com.dcy.znoa.domain.attendance.AttRuleAddress;
import com.dcy.znoa.domain.publiz.Company;
import com.dcy.znoa.domain.publiz.Department;
import com.dcy.znoa.domain.sys.OperRole;
import com.dcy.znoa.service.attendance.AttRuleService;
import com.dcy.znoa.service.publiz.CompanyService;
import com.dcy.znoa.service.publiz.DepartmentService;
import com.dcy.znoa.service.software.OperService;
import com.dcy.znoa.service.sys.OperRoleService;
import com.google.common.base.Strings;
import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.lang.reflect.InvocationTargetException;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.TimeZone;

@Service
public class AttRuleServiceImpl implements AttRuleService {
    @Autowired
    AttRuleDao attRuleDao;
    @Autowired
    OperDao operDao;
    @Autowired
    AttRuleAddressDao attRuleAddressDao;

    @Transactional
    @Override
    public synchronized Integer insert(AttRule attRule) throws BusinessException {
        if (attRule == null) {
            return 0;
        }
        Integer attRuleNo;
        Integer attRuleNoParm = attRule.getAttRuleNo();
        Long compId = attRule.getCompId();
        if (attRuleNoParm == null) {
            //按compId 查询，在最大的那里加一
            attRuleNo = getNextAttRuleNo(compId);
            attRule.setAttRuleNo(attRuleNo);
        } else {
            attRuleNo = attRuleNoParm;
        }
        if (attRule.getStartTime().after(attRule.getEndTime())) {
            throw new BusinessException("404", "开始时间不能大于结束时间");
        }
        //AttRuleSerial 在单个compId + AttRuleNo 自增
        attRule.setAttRuleSerial(getNextAttRuleSerial(compId, attRuleNo));
        String[] longArray = attRule.getLongitude().split(",");
        String[] latArray = attRule.getLatitude().split(",");
        String[] addressArray = attRule.getAddress().split(",");
        for (int i = 0; i < longArray.length; i++) {
            AttRuleAddress attRuleAddress = new AttRuleAddress(null, attRuleNo, compId, longArray[i], latArray[i], addressArray[i]);
            attRuleAddressDao.insert(attRuleAddress);
        }

        return attRuleDao.insert(attRule);
    }

    @Transactional
    @Override
    public Integer updateById(AttRule attRule) throws BusinessException {
        if (attRule.getStartTime().after(attRule.getEndTime())) {
            throw new BusinessException("404", "开始时间不能大于结束时间");
        }
        Integer attRuleNo = attRule.getAttRuleNo();
        Long compId = attRule.getCompId();
        Integer resultAttRule = attRuleDao.updateById(attRule);
        //先做物理删除，再插入AttRuleAddress表
        String longitude =  attRule.getLongitude();
        String latitude =  attRule.getLatitude();
        String address =  attRule.getAddress();
        if(StringUtils.isNotBlank(longitude)&&StringUtils.isNotBlank(latitude)&&StringUtils.isNotBlank(address)){
            Integer resultAddress = attRuleAddressDao.delete(new EntityWrapper<AttRuleAddress>().eq("comp_id", attRule.getCompId()).eq("att_rule_no", attRuleNo));
//            if (resultAddress <= 0 || resultAttRule <= 0) {
//                throw new BusinessException("404", "规则更新内部失败");
//            }
            if (resultAttRule <= 0) {
                throw new BusinessException("404", "规则更新内部失败");
            }
            String[] longArray = longitude.split(",");
            String[] latArray = latitude.split(",");
            String[] addressArray = address.split(",");
            for (int i = 0; i < longArray.length; i++) {
                AttRuleAddress attRuleAddress = new AttRuleAddress(null, attRuleNo, compId, longArray[i], latArray[i], addressArray[i]);
                attRuleAddressDao.insert(attRuleAddress);
            }
        }
        return 1;
    }

    @Override
    public Integer validFlag(AttRule attRuleQuery) throws BusinessException, InvocationTargetException, IllegalAccessException {
        AttRule attRule = attRuleDao.selectById(attRuleQuery.getAttRuleId());
        if(attRule==null || attRule.getAttRuleNo()==null ||attRule.getCompId()==null ){
            throw new BusinessException("404", "此规则不存在或信息不全，请联系管理员");
        }
        checkOper(attRule);
        BeanUtils.copyProperties(attRule, attRuleQuery);
        attRule.setValidFlag(0);
        return attRuleDao.updateById(attRule);
    }
    @Transactional
    @Override
    public Integer delete(Long attRuleId) throws BusinessException {
        AttRule attRule = attRuleDao.selectById(attRuleId);
        checkOper(attRule);
        if(attRule==null || attRule.getAttRuleNo()==null ||attRule.getCompId()==null ){
            throw new BusinessException("404", "此规则不存在或信息不全，请联系管理员");
        }
        attRuleDao.deleteById(attRuleId);
        attRuleAddressDao.delete(new EntityWrapper<AttRuleAddress>().eq("comp_id", attRule.getCompId()).eq("att_rule_no", attRule.getAttRuleNo()));
        return 1;
    }

    //查询是否有关联用户
    public void checkOper(AttRule attRule) throws BusinessException {
        Integer attRuleNo = attRule.getAttRuleNo();
        Long compId = attRule.getCompId();
        if (attRuleNo == null || compId == null) {
            throw new BusinessException("404", "规则ID " + attRule.getAttRuleId() + " 对应的企业id或规则编号为空，请联系管理员");
        }
        List list = operDao.selectList(new EntityWrapper<Oper>().eq("comp_id", compId).eq("att_rule_no", attRuleNo));
        if (!list.isEmpty()) {
            throw new BusinessException("404", "此规则已关联用户，不能禁用");
        }
    }

    @Override
    public JsonForList queryListMapper(SelectAttRuleModel model) {
        Page page = new Page(model.getPageNum(), model.getPageSize());
        List list = attRuleDao.queryListMapper(model, page);
        return new JsonForList(list, page.getTotal());
    }

    //APP  查询单人的规则，以及地址列表
    @Override
    public AttRule queryByOperId(Long operId) throws BusinessException, ParseException {
        AttRule attRule = null;
        Oper oper = operDao.selectById(operId);
        if (oper == null) {
            throw new BusinessException("404", "此用户不存在");
        }
        Long compId = oper.getCompId();
        Integer attRuleNo = oper.getAttRuleNo();
        if (attRuleNo == null) {
            //把默认的规则赋予 这个用户
            //查询默认的规则
            attRule = attRuleDao.selectOne(new AttRule(1, oper.getCompId()));
            if (attRule == null) {
                //先新增一个默认的企业考勤规则
                DateFormat df = DateFormat.getTimeInstance();//只显示出时分秒
//                Date st1 = DateUtil.datetimeFormat_1
                Date st = DateUtil.datetimeFormat_MHS.parse("09:00:00");
                Date et = DateUtil.datetimeFormat_MHS.parse("18:00:00");
                attRuleNo = getNextAttRuleNo(compId);
//                attRuleDefault = new AttRule(1,"默认规则","不允许删除",1,1,compId,new Date(df3.format(st)),new Date(df3.format(et)),12,500,new Date(),null,null,null,1);
                attRule = new AttRule(attRuleNo, "默认规则", "不允许删除", 1, 1, compId, st, et, 12, 500, new Date(), 15L, 1);//15是cook的id
                attRuleDao.insert(attRule);
            }
            oper.setAttRuleNo(attRuleNo);
            operDao.updateById(oper);
        }else {
            AttRule attRuleQuery = new AttRule();
            attRuleQuery.setCompId(compId);
            attRuleQuery.setAttRuleNo(attRuleNo);
            attRule = attRuleDao.selectOne(attRuleQuery);
            if(attRule==null){
                throw new BusinessException("404","用户数据异常，请联系管理员");
            }
        }
        AttRuleAddress attRuleAddress = new AttRuleAddress();
        EntityWrapper ew =  new EntityWrapper<AttRuleAddress>();
        ew.setEntity(attRuleAddress);
        ew.eq("comp_id", compId).eq("att_rule_no", attRuleNo);
        List<AttRuleAddress> list = attRuleAddressDao.selectList(ew);
        attRule.setAttRuleAddressList(list);
        return  attRule;
    }

    @Override
    public AttRule getById(Long attRuleId) {
        AttRule attRule = attRuleDao.selectById(attRuleId);
        if(attRule==null){
            return null;
        }
        AttRuleAddress attRuleAddress = new AttRuleAddress();
        EntityWrapper ew =  new EntityWrapper<AttRuleAddress>();
        ew.setEntity(attRuleAddress);
        ew.eq("comp_id", attRule.getCompId()).eq("att_rule_no", attRule.getAttRuleNo());
        List<AttRuleAddress> list = attRuleAddressDao.selectList(ew);
        attRule.setAttRuleAddressList(list);
        return attRule;
    }

    //查询下个 规则编号
    public Integer getNextAttRuleNo(Long compId) {
        if (compId == null) {
            return null;
        }
//        List<AttRule> list = attRuleDao.selectListMapper(new EntityWrapper<AttRule>().where(" comp_id = " + compId + " order by att_rule_no desc  limit 1", null));
        List<AttRule> list = attRuleDao.selectList(new EntityWrapper<AttRule>().last(" where comp_id = " + compId + " order by att_rule_no desc  limit 1"));

        if (!list.isEmpty()) {
            return list.get(0).getAttRuleNo() + 1;
        }
        return 1;//
    }

    //查询下个 规则编号下的 规则序号
    public Integer getNextAttRuleSerial(Long compId, Integer attRuleNo) {
        if (compId == null || attRuleNo == null) {
            return null;
        }
//        AttRule attRule ;
        List<AttRule> list = attRuleDao.selectList(new EntityWrapper<AttRule>().last(" where comp_id = " + compId + " and  att_rule_no = " + attRuleNo + " order by att_rule_serial desc  limit 1"));
        if (!list.isEmpty()) {
            return list.get(0).getAttRuleNo() + 1;
        }
        return 1;//
    }
    public static void main(String args[]) throws ParseException {
//        Date st = new Date("2017-01-01 09:00:00");
        Date st = DateUtil.dateFormat.parse("2017-01-01 09:00:00");
//        DateUtil.dateFormat.setTimeZone(TimeZone.getTimeZone("Asia/Shanghai"));
        System.out.print(st);
        SimpleDateFormat sdf1 = new SimpleDateFormat("HH:mm:ss");//yyyy-MM-dd
        Date d = sdf1.parse("21:22:23");
//        String str1 = sdf1.format("2018-01-01 09:00:00");
//        String str1 = sdf1.format(new Date());
        System.out.println("----:"+d);//日期会按照模板的样子转String
    }

}
